import 'package:beamer/beamer.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/foundation.dart' show defaultTargetPlatform, TargetPlatform, kIsWeb;
import 'package:rabbit_mobile/view/UserProfilePage/index.dart';
import 'package:rabbit_mobile/theme/index.dart';

import '../../provide/riverpod_provider.dart';
import '../../service/home.api.dart';
import '../../theme/index.dart';
import '../webview_flutter/index.dart';

class Mine extends ConsumerStatefulWidget {
  const Mine({super.key});

  @override
  _MineState createState() => _MineState();
}

class _MineState extends ConsumerState<Mine> with SingleTickerProviderStateMixin {
  late final TabController _tabController;
  late final PageController _pageController;
  Map<String, dynamic>? _userProfileData;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _pageController = PageController();
    _fetchUserData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  Future<void> _fetchUserData() async {
    final result = await GetUserProfileInformation.getUserProfileInformationFetch();
    if (!mounted) return;
    setState(() {
      _userProfileData = result;
    });
  }

  double _platformDiff(BuildContext context) {
    if (kIsWeb) return 0;
    if (defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS) {
      return kTextTabBarHeight;
    }
    return 0;
  }

  @override
  Widget build(BuildContext context) {
    final imageProvider = (_userProfileData != null && (_userProfileData?['avatar']?.isNotEmpty ?? false))
        ? NetworkImage(_userProfileData!['avatar']) as ImageProvider
        : const AssetImage('assets/placeholder.png');

    return Scaffold(
      body: SizedBox.expand(
        child: Stack(
          children: [
            const AppbarWidget(),
            Positioned(
              top: _platformDiff(context),
              right: 0,
              left: 0,
              bottom: 0,
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    child: Column(
                      children: [
                        const SizedBox(height: 12),
                        Row(
                          children: [
                            SizedBox(
                              width: 50,
                              height: 50,
                              child: CircleAvatar(
                                backgroundImage: imageProvider,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Text(
                                        _userProfileData?['nickname'] ?? '',
                                        style: const TextStyle(color: Colors.white, fontSize: 14),
                                      ),
                                      const SizedBox(width: 10),
                                      Container(
                                        padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 4),
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.circular(4),
                                        ),
                                        child: const Text(
                                          '白金',
                                          style: TextStyle(color: Color(0xFF00D0AC), fontSize: 14),
                                        ),
                                      )
                                    ],
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      if (_userProfileData!.isNotEmpty) {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => MyWebViewPage(
                                              title: "个人中心",
                                              userProfileData: _userProfileData,
                                            ),
                                          ),
                                        );
                                      } else {
                                        Beamer.of(context).beamToNamed('login');
                                      }
                                    },
                                    child: Container(
                                      margin: const EdgeInsets.only(top: 6),
                                      padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 8),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(25),
                                      ),
                                      child: const Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Text(
                                            '賬戶管理',
                                            style: TextStyle(color: Color(0xFF00D0AC), fontSize: 14),
                                          ),
                                          Icon(
                                            Icons.arrow_right_rounded,
                                            color: Color(0xFF00D0AC),
                                            size: 22,
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                        const SizedBox(height: 20),
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: const [
                                  Text('我的訂單'),
                                  Row(
                                    children: [
                                      Text('查看全部訂單'),
                                      SizedBox(width: 10),
                                      Icon(Icons.arrow_forward_ios_rounded, size: 16, color: Colors.grey)
                                    ],
                                  )
                                ],
                              ),
                              const SizedBox(height: 10),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: ['daifukuan', 'daifahuo', 'daishouhuo', 'daishouhuo', 'shouhou']
                                    .map((asset) => Column(
                                          children: [
                                            Image.asset('assets/$asset.png', width: 30, height: 30),
                                            const SizedBox(height: 4),
                                            Text(
                                              asset == 'daifukuan'
                                                  ? '待付款'
                                                  : asset == 'daifahuo'
                                                      ? '待發貨'
                                                      : asset == 'daishouhuo'
                                                          ? '待收貨'
                                                          : asset == 'shouhou'
                                                              ? '售後'
                                                              : '待評價',
                                              style: const TextStyle(fontSize: 14, color: Colors.black),
                                            )
                                          ],
                                        ))
                                    .toList(),
                              )
                            ],
                          ),
                        ),
                        const SizedBox(height: 20),
                        TabBar(
                          controller: _tabController,
                          indicatorColor: Colors.green,
                          labelColor: Colors.black,
                          onTap: (index) => _pageController.animateToPage(
                            index,
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                          ),
                          tabs: const [
                            Tab(text: 'Home'),
                            Tab(text: 'Work'),
                            Tab(text: 'Play'),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: PageView(
                      controller: _pageController,
                      onPageChanged: (index) => _tabController.animateTo(index),
                      children: [
                        Center(
                            child: GestureDetector(
                          onTap: () {
                            Navigator.push(context, MaterialPageRoute(builder: (context) => ChangeThemeWidget()));
                          },
                          child: Container(
                            width: 100,
                            height: 100,
                            child: Text("theme"),
                          ),
                        )),
                        const Center(child: Text('2')),
                        const Center(child: Text('3')),
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class AppbarWidget extends StatelessWidget implements PreferredSizeWidget {
  const AppbarWidget({super.key});

  @override
  Size get preferredSize => const Size.fromHeight(150 + kTextTabBarHeight);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: preferredSize.height,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/mine_nav_bg.png'),
          fit: BoxFit.fill,
        ),
      ),
    );
  }
}
